#!/bin/bash
set -e

# 设置源
MIRROR_APT_URL="mirrors.tuna.tsinghua.edu.cn"

UBUNTU_RELEASE=`lsb_release -sr`
UBUNTU_CODENAME=`lsb_release -sc`


ROS_DEP_PATH="/usr/lib/python2.7/dist-packages/rosdep2"
ROS_DEP_PKG="python-rosdep python-rosinstall python-rosinstall-generator python-wstool build-essential"

if [[ "${UBUNTU_RELEASE}" == "16.04" ]]; then
	echo "${UBUNTU_RELEASE}"
	ROS_VERSION="kinetic"
elif [[ "${UBUNTU_RELEASE}" == "18.04" ]]; then
    echo "${UBUNTU_RELEASE}"
    ROS_VERSION="melodic"
elif [[ "${UBUNTU_RELEASE}" == "20.04" ]]; then
	echo "${UBUNTU_RELEASE}"
	ROS_DEP_PATH="/usr/lib/python3/dist-packages/rosdep2"
	ROS_DEP_PKG="python3-rosdep python3-rosinstall python3-rosinstall-generator python3-wstool build-essential"
	ROS_VERSION="noetic"
fi


add_line()
{
    if (! grep -Fxq "$1" "$2"); then
        echo $1 >> $2;
    else
        echo "add_line(): \"$1\" already in $2.";
    fi
}


echo 'using tsinghua source'
ros_mirror_text="deb http://${MIRROR_APT_URL}/ros/ubuntu/ $UBUNTU_CODENAME main"
echo -e ${ros_mirror_text} | sudo tee /etc/apt/sources.list.d/ros-latest.list
sudo apt-key adv --keyserver 'hkp://keyserver.ubuntu.com:80' --recv-key C1CF6E31E6BADE8868B172B4F42ED6FBAB17C654
sudo apt update

#sudo sh -c '. /etc/lsb-release && echo "deb http://${MIRROR_APT_URL}/ros/ubuntu/ $UBUNTU_CODENAME main" > /etc/apt/sources.list.d/ros-latest.list'
# curl -s http://raw.githubusercontent.com/ros/rosdistro/master/ros.asc | sudo apt-key add -
# curl -s http://gitcode.net/mirrors/ros/rosdistro/-/raw/master/ros.asc | sudo apt-key add -


# sudo apt install ros-melodic-desktop-full -y
sudo apt install ros-$ROS_VERSION-desktop-full -y

sudo apt install ${ROS_DEP_PKG} -y
sudo apt install python3-catkin-tools -y

# sudo apt install ros-melodic-mavros ros-melodic-mavros-extras -y
sudo apt install ros-$ROS_VERSION-mavros ros-$ROS_VERSION-mavros-extras -y

add_line "source /opt/ros/$ROS_VERSION/setup.bash" ~/.bashrc
add_line "source /opt/ros/$ROS_VERSION/setup.zsh" ~/.zshrc

source ~/.bashrc

# 使用清华源解决rosdep的问题
# 手动模拟rosdep init
sudo mkdir -p /etc/ros/rosdep/sources.list.d/
sudo curl -o /etc/ros/rosdep/sources.list.d/20-default.list http://mirrors.tuna.tsinghua.edu.cn/github-raw/ros/rosdistro/master/rosdep/sources.list.d/20-default.list

# 为 rosdep update 换源
export ROSDISTRO_INDEX_URL=http://mirrors.tuna.tsinghua.edu.cn/rosdistro/index-v4.yaml
rosdep update

add_line "export ROSDISTRO_INDEX_URL=http://mirrors.tuna.tsinghua.edu.cn/rosdistro/index-v4.yaml" ~/.bashrc
add_line "export ROSDISTRO_INDEX_URL=http://mirrors.tuna.tsinghua.edu.cn/rosdistro/index-v4.yaml" ~/.zshrc